import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login } from '../api'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(JSON.parse(sessionStorage.getItem('userInfo') || 'null'))
  const token = ref(sessionStorage.getItem('token') || '')

  // 登录
  const loginAction = async (loginData) => {
    try {
      const response = await login(loginData)
      const userData = response.data
      
      // 保存用户信息和token
      userInfo.value = userData
      token.value = userData.token
      
      sessionStorage.setItem('userInfo', JSON.stringify(userData))
      sessionStorage.setItem('token', userData.token)
      
      return userData
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = () => {
    userInfo.value = null
    token.value = ''
    sessionStorage.removeItem('userInfo')
    sessionStorage.removeItem('token')
  }

  // 获取用户角色
  const getUserRole = () => {
    return userInfo.value?.role || ''
  }

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!token.value && !!userInfo.value
  }

  return {
    userInfo,
    token,
    loginAction,
    logout,
    getUserRole,
    isLoggedIn
  }
}) 